package org.example;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.*;

/**
 * 独占锁（写锁）
 * 共享锁（读锁）
 * 读写锁的使用
 * 读写者问题：
 * 1. 读者 - 读者   共享
 * 2. 读者 - 写者   互斥
 * 3. 写者 - 写者   互斥
 */
public class ReadWriteLockDemo {

    public static void main(String[] args) {
//        MyCache myCache = new MyCache();
        MyCacheReadWriteLock myCache = new MyCacheReadWriteLock();

        for (int i = 0; i < 5; i++) {
            final int tmp = i;
            new Thread(() -> {
                myCache.write(Thread.currentThread().getName(), tmp);
            }, String.valueOf(i)).start();
        }
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                myCache.read(Thread.currentThread().getName());
            }, String.valueOf(i)).start();
        }
    }
}

// 自定义缓存
// 通过 synchronized关键字，锁的都是同一个对象
// 虽然实现了互斥，但没有满足条件1
// 因此需要粒度更小的锁
class MyCache {

    private final Map<String, Integer> map = new HashMap();

    // 读
    public synchronized void read(String k) {
        System.out.println(Thread.currentThread().getName() + "开始读取" + k);
        Integer v = map.get(k);
        System.out.println(Thread.currentThread().getName() + "读取完成" + k + ":" + v);
    }

    // 写
    public synchronized void write(String k, Integer v) {
        System.out.println(Thread.currentThread().getName() + "开始写入" + k + ":" + v);
        map.put(k, v);
        System.out.println(Thread.currentThread().getName() + "完成写入" + k);
    }
}

// 使用读写锁
class MyCacheReadWriteLock {

    private final Map<String, Integer> map = new HashMap();
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private final Lock readLock = readWriteLock.readLock();
    private final Lock writeLock = readWriteLock.writeLock();

    // 读
    public void read(String k) {
        readLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "开始读取" + k);
            Integer v = map.get(k);
            System.out.println(Thread.currentThread().getName() + "读取完成" + k + ":" + v);
        } finally {
            readLock.unlock();
        }
    }

    // 写
    public void write(String k, Integer v) {
        writeLock.lock();
        try{
            System.out.println(Thread.currentThread().getName() + "开始写入" + k + ":" + v);
            map.put(k, v);
            System.out.println(Thread.currentThread().getName() + "完成写入" + k);
        }finally {
            writeLock.unlock();
        }
    }
}